package com.chenjl.exchange;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.Channel;

import com.chenjl.transport.AbstractClient;
import com.chenjl.transport.HookChannelHandler;
import com.chenjl.transport.support.NettyClient;
/**
 * 基于NettyClient实现同步请求
 * 2016-9-7 16:12:48
 * @author chenjinlong
 */
public class ExchangeClient {
	private static final Logger logger = LoggerFactory.getLogger(ExchangeClient.class);
	
	private AbstractClient client;
	private HookChannelHandler hookChannelHandler = new HookChannelHandler() {
		@Override
		public void channelRead(Channel channel,Object msg) throws Exception {
			logger.info("client receive message from server : {}",msg);
			if(msg.getClass() == Response.class) {
				Response response = (Response) msg;
				ResponseFuture.handlerResponse(response);
			}
			else {
				logger.error("client receive message from server : {}, can not handle ",msg);
			}
		}
	};
	
	public ExchangeClient(String serverAddr) {
		this.client = new NettyClient(serverAddr,hookChannelHandler);
		client.connect();
	}
	
	/**
	 * 发送消息，同步等待消息返回
	 * @param object
	 * @return
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public Object send(Object object) throws InterruptedException, ExecutionException {
		Request request = new Request();
		request.setData(object);
		ResponseFuture responseFuture = new ResponseFuture(request);
		client.send(request);
		
		return responseFuture.get();
	}
	/**
	 * 发送消息后，返回Future，由NIO异步通知完成
	 * @param object
	 * @return
	 */
	public Future<Object> asyncSend(Object object) {
		Request request = new Request();
		request.setData(object);
		ResponseFuture responseFuture = new ResponseFuture(request);
		client.send(request);
		
		return responseFuture;
	}
	public void close() {
		client.close();
		ResponseFuture.clear();
	}
}